package org.mall.modules.cash.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.mall.common.api.vo.Result;
import org.mall.common.aspect.annotation.AutoLog;
import org.mall.common.constant.CashInfoLogResultEnum;
import org.mall.common.system.query.QueryGenerator;
import org.mall.common.system.util.JwtUtil;
import org.mall.common.util.DateUtil;
import org.mall.common.util.json.JacksonUtils;
import org.mall.common.util.oConvertUtils;
import org.mall.convert.order.CashInfoLogConvert;
import org.mall.modules.cash.entity.CashDetailInfo;
import org.mall.modules.cash.entity.CashInfoLog;
import org.mall.modules.cash.service.ICashInfoLogService;
import org.mall.modules.cash.service.ISellerCashInfoService;
import org.mall.modules.order.service.OrderService;
import org.mall.modules.pojo.cash.CashInfoLogConfiremVO;
import org.mall.modules.pojo.cash.CashInfoLogQueryDTO;
import org.mall.modules.pojo.cash.CashInfoLogVO;
import org.mall.modules.pojo.order.bo.OrderBO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 提现信息记录表
 * @Author: jeecg-boot
 * @Date: 2019-12-31
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "提现信息记录表")
@RestController
@RequestMapping("/cash")
public class CashInfoLogController {
    @Autowired
    private ICashInfoLogService cashInfoLogService;

    @Autowired
    private ISellerCashInfoService sellerCashInfoService;

    @Autowired
    private OrderService orderService;

    /**
     * 分页列表查询
     *
     * @param cashInfoLog
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "提现信息记录表-分页列表查询")
    @ApiOperation(value = "提现信息记录表-分页列表查询", notes = "提现信息记录表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<CashInfoLog>> queryPageList(CashInfoLog cashInfoLog,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        Result<IPage<CashInfoLog>> result = new Result<IPage<CashInfoLog>>();
        QueryWrapper<CashInfoLog> queryWrapper = QueryGenerator.initQueryWrapper(cashInfoLog, req.getParameterMap());
        Page<CashInfoLog> page = new Page<CashInfoLog>(pageNo, pageSize);
        IPage<CashInfoLog> pageList = cashInfoLogService.pageList(page, queryWrapper);
        CashInfoLogConvert.INSTANCE.convert1(pageList.getRecords()).forEach(o -> {
        });
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param cashInfoLog
     * @return
     */
    @AutoLog(value = "提现信息记录表-添加")
    @ApiOperation(value = "提现信息记录表-添加", notes = "提现信息记录表-添加")
    @PostMapping(value = "/add")
    public Result<CashInfoLog> add(@RequestBody CashInfoLog cashInfoLog) {
        Result<CashInfoLog> result = new Result<CashInfoLog>();
        try {
            cashInfoLogService.save(cashInfoLog);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param cashInfoLog
     * @return
     */
    @AutoLog(value = "提现信息记录表-编辑")
    @ApiOperation(value = "提现信息记录表-编辑", notes = "提现信息记录表-编辑")
    @PutMapping(value = "/edit")
    public Result<CashInfoLog> edit(@RequestBody CashInfoLog cashInfoLog) {
        Result<CashInfoLog> result = new Result<CashInfoLog>();
        CashInfoLog cashInfoLogEntity = cashInfoLogService.getById(cashInfoLog.getId());
        if (cashInfoLogEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = cashInfoLogService.updateById(cashInfoLog);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "提现信息记录表-通过id删除")
    @ApiOperation(value = "提现信息记录表-通过id删除", notes = "提现信息记录表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            cashInfoLogService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "提现信息记录表-批量删除")
    @ApiOperation(value = "提现信息记录表-批量删除", notes = "提现信息记录表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<CashInfoLog> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<CashInfoLog> result = new Result<CashInfoLog>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.cashInfoLogService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "提现信息记录表-通过id查询")
    @ApiOperation(value = "提现信息记录表-通过id查询", notes = "提现信息记录表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<CashInfoLog> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<CashInfoLog> result = new Result<CashInfoLog>();
        CashInfoLog cashInfoLog = cashInfoLogService.getById(id);
        if (cashInfoLog == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(cashInfoLog);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<CashInfoLog> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                CashInfoLog cashInfoLog = JSON.parseObject(deString, CashInfoLog.class);
                queryWrapper = QueryGenerator.initQueryWrapper(cashInfoLog, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<CashInfoLog> pageList = cashInfoLogService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "提现信息记录表列表");
        mv.addObject(NormalExcelConstants.CLASS, CashInfoLog.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("提现信息记录表列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CashInfoLog> listCashInfoLogs = ExcelImportUtil.importExcel(file.getInputStream(), CashInfoLog.class, params);
                cashInfoLogService.saveBatch(listCashInfoLogs);
                return Result.ok("文件导入成功！数据行数:" + listCashInfoLogs.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    @GetMapping("/detail")
    public Result getCashInfoLogDetail(@RequestParam String id) {
        Long infoId = Long.parseLong(id);
        CashInfoLog cashInfoLog = cashInfoLogService.getDetailById(infoId);
        List<Long> orderIdList = cashInfoLog.getDetailInfos().stream().map(CashDetailInfo::getOrderId).collect(Collectors.toList());

        List<OrderBO> orderBOList = orderService.getOrdersByIds(orderIdList);

        CashInfoLogVO vo = CashInfoLogConvert.INSTANCE.convert2(cashInfoLog);
        vo.setOrderList(orderBOList);
        return Result.ok(vo);
    }

    @PostMapping("/confirm")
    @Transactional
    public Result confirm(@RequestBody CashInfoLogConfiremVO vo) throws Exception {

        CashInfoLog cashInfoLog = cashInfoLogService.getDetailById(vo.getCashInfoLogId());
        if (cashInfoLog == null | cashInfoLog.getDeleted() == 1) {
            return Result.error("申请记录不存在");
        }
        if (!cashInfoLog.getResult().equals(CashInfoLogResultEnum.REVIEWING.getValue())) {
            return Result.error("此条审核已被处理");
        }
        if (CashInfoLogResultEnum.PAYING.getValue().equals(cashInfoLog.getResult())){
            return Result.error("此条申请记录处于提现中");
        }
        List<Long> ids = cashInfoLog.getDetailInfos().stream().map(CashDetailInfo::getCashId).collect(Collectors.toList());
        if (!sellerCashInfoService.updateStatusToSuccess(ids)||!cashInfoLogService.confirm(vo.getCashInfoLogId(),vo.getPayChannel())){
            throw new Exception("");
        }
        return Result.ok(true);


    }

    @GetMapping("/getTransactionLog")
    //获取交易记录
    public Result<?> getTransactionLog(@RequestParam Long cashId){

        return  cashInfoLogService.getTransactionLog(cashId);
    }
    @PostMapping("/refuse")
    @Transactional
    public Result refuse(@RequestBody CashInfoLogConfiremVO vo) throws Exception {

        CashInfoLog cashInfoLog = cashInfoLogService.getDetailById(vo.getCashInfoLogId());
        if (cashInfoLog == null | cashInfoLog.getDeleted() == 1) {
            return Result.error("申请记录不存在");
        }
        if (!cashInfoLog.getResult().equals(CashInfoLogResultEnum.REVIEWING.getValue())) {
            return Result.error("此条审核已被处理");
        }

        List<Long> ids = cashInfoLog.getDetailInfos().stream().map(CashDetailInfo::getCashId).distinct().collect(Collectors.toList());
        if (!sellerCashInfoService.updateStatusToFailure(ids)||! cashInfoLogService.refuse(vo.getCashInfoLogId(), vo.getResponse() == null ? "" : vo.getResponse())){
            throw new Exception("");
        }

        return Result.ok(true);

    }



    @GetMapping("/seller/getCashInfoLogById")
    public Result getCashInfoForSeller(@RequestParam Long cashInfoLogId){
        CashInfoLog cashInfoLog=cashInfoLogService.getDetailById(cashInfoLogId);
        if (cashInfoLog==null||!JwtUtil.getUserIdByToken().equals(cashInfoLog.getSellerId())){
            return Result.error("无权限查看这条提现记录");
        }
        List<OrderBO> bos=orderService.getOrderByIds(cashInfoLog.getDetailInfos().stream().map(CashDetailInfo::getOrderId).collect(Collectors.toList()));
        CashInfoLogVO cashInfoLogVO=CashInfoLogConvert.INSTANCE.convert2(cashInfoLog);
        cashInfoLogVO.setOrderList(bos);
        return Result.ok(cashInfoLogVO);
    }

    @GetMapping("/seller/getCashInfoLogList")
    public Result getCashInfoLogListForSeller(@RequestParam Integer pageNo,@RequestParam Integer pageSize,@RequestParam Integer type){

        CashInfoLogQueryDTO cashInfoLog=new CashInfoLogQueryDTO();
        Calendar cal = Calendar.getInstance();
        switch (type){
            case  1:
                cashInfoLog.setCreateStartTime(DateUtil.getDayBegin());
                cashInfoLog.setCreateEndTime(DateUtil.getDayEnd());
                break;
            case 2:
                cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                Date date = cal.getTime();
                cashInfoLog.setCreateStartTime(DateUtil.getDayBegin(date));
                cal.add(Calendar.DATE,6);
                cashInfoLog.setCreateEndTime(DateUtil.getDayEnd(cal.getTime()));
                break;
            case 3:
                cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
                cashInfoLog.setCreateStartTime(DateUtil.getDayBegin(cal.getTime()));
                cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
                cashInfoLog.setCreateEndTime(DateUtil.getDayEnd(cal.getTime()));
            case  4:
                cal.set(Calendar.DAY_OF_YEAR, 1);
                cashInfoLog.setCreateStartTime(DateUtil.getDayBegin(cal.getTime()));
                cal.set(Calendar.DAY_OF_YEAR, 1);                //获取本年最后一天
                cal.set(Calendar.YEAR, 1);
                cal.add(Calendar.DAY_OF_YEAR, -1);
                cashInfoLog.setCreateEndTime(DateUtil.getDayEnd(cal.getTime()));
            default:
                break;

        }
        cashInfoLog.setSellerId(JwtUtil.getUserIdByToken());
        log.info(JacksonUtils.toJSONString(cashInfoLog));
        Page  page=new Page().setCurrent(pageNo).setSize(pageSize);
        return Result.ok(cashInfoLogService.pageListByCondition(page,cashInfoLog));

    }

}
